<?php

/**
 * @author ducnhat
 * @email ddnhat@gmail.com
 * @copyright 2014
 */

class Admin_Model_Setting extends Zend_Db_Table{
	
	protected $_name    = "options";
    protected $_primary = "id";
    
    public function saveData($data = array()){
    	$db = Zend_Registry::get('db');
        
        $db->beginTransaction();
        
        try{
            if($this->checkExists($data['key'])){
                $key = $data['key'];
                $db->update("options", $data, "`key` = '$key'");
            }else{
                $db->insert('options', $data);
            }
            
            $cache = new Zenddn_System_Cache();
            $cache->clean(array('setting'));
            
            $db->commit();
            
            return true;
        }catch(Exception $e){
            $db->rollBack();
            
            return false;
        }
    }
    
    public function getData($key = null){
    	$db = Zend_Registry::get('db');
        $db->setFetchMode(Zend_Db::FETCH_OBJ);
        
        $cols = array('id', 'key', 'value');
        
        $select = $db->select()
                    ->from(array('o' => 'options'), $cols);
        
        if($key != null){
            $select->where("o.key = ?", $key);
            
            $db->setFetchMode(Zend_Db::FETCH_ASSOC);
            $result = $db->fetchRow($select);
        }else{
            $result = $db->fetchAll($select);
        }
        
        return $result;
    }
    
    public function getAllData(){
    	return $this->getData();
    }
    
    public function deleteData($key){
    	$db = Zend_Registry::get('db');
        
        $db->beginTransaction();
        
        try{
            $db->delete('options', "`key` = '$key'");
            
            $cache = new Zenddn_System_Cache();
            $cache->clean(array('setting'));
            
            $db->commit();
            
            return true;
        }catch(Exception $e){
            $db->rollBack();
            
            return false;
        }
    }
    
    public function checkExists($key){
        $option = array('table' => 'options', 'field' => 'key');
    	$validator = new Zend_Validate_Db_RecordExists($option);
        
        if($validator->isValid($key)){
            return true;
        }
        
        return false;
    }
}